package com.zcf.shiro.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 跨境主库数据源配置
 * @author Tao, yingfei
 */
@Configuration
@AutoConfigureAfter(JzwjgDsc.class)
@MapperScan(basePackages = {JzwjgDataSourceConfig.PACKAGE1, JzwjgDataSourceConfig.PACKAGE2}, sqlSessionFactoryRef = "jzwjgSqlSessionFactory")
public class JzwjgDataSourceConfig {

    static final String PACKAGE1 = "com.zcf.shiro.idcentity.custom.mapper";
    static final String PACKAGE2 = "com.zcf.shiro.idcentity.major.mapper";
    static final String MAPPER_LOCATION = "classpath*:com/zcf/shiro/idcentity/mapper/xml/*.xml";

    @Autowired
    @Qualifier("jzwjgDataSource")
    private DataSource jzwjgDataSource;

    @Bean(name = "jzwjgTransactionManager")
    @Primary
    public DataSourceTransactionManager jzwjgTransactionManager() {
        return new DataSourceTransactionManager(jzwjgDataSource);
    }

    @Bean(name = "jzwjgSqlSessionFactory")
    @Primary
    public SqlSessionFactory jzwjgSqlSessionFactory(@Qualifier("jzwjgDataSource") DataSource jzwjgDataSource)
            throws Exception {
        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(jzwjgDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(JzwjgDataSourceConfig.MAPPER_LOCATION));
        Interceptor[] interceptor = {pageInterceptor()};
        sessionFactory.setPlugins(interceptor);
        return sessionFactory.getObject();
    }

    @Bean
    public PaginationInterceptor pageInterceptor() {
        PaginationInterceptor pageInterceptor = new PaginationInterceptor();
        pageInterceptor.setDialectType(DbType.ORACLE.getDb());
        return pageInterceptor;
    }
}